package cn.oyjg.debugTool;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;
import java.io.File;
import java.io.IOException;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.plaf.FontUIResource;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

import org.apache.log4j.Logger;
import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.sun.javafx.application.PlatformImpl;

import cn.oyjg.debugTool.db.SQLiteHelper;
import cn.oyjg.debugTool.entity.Action;
import cn.oyjg.debugTool.entity.Category;
import cn.oyjg.debugTool.entity.Param;
import cn.oyjg.debugTool.util.HttpClient;
import cn.oyjg.debugTool.util.JsonFormatTool;
import cn.oyjg.debugTool.util.JsonValidator;
import cn.oyjg.debugTool.util.MD5Util;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebView;
import javax.swing.JRadioButton;

/**
 * Hello world!
 *
 */
public class App {
	private JFrame frmv;
	public JTable table;
	private JTextField txt_url;
	private JTree tree;
	private JComboBox<String> comboBox; 
	private JEditorPane txt_Pane ;
	public JLabel lbl_status;
	private SQLiteHelper sqlHelp = new SQLiteHelper();
	private JsonValidator jsonValidator=new JsonValidator(); 
	private Logger log=Logger.getLogger(App.class);
	private JScrollPane scrollPane; 
	private JScrollPane scrollPane_1;
	private JLabel lbl_jsonValidate;
	private DefaultMutableTreeNode m_rootNode = new DefaultMutableTreeNode(new Category("模块", 0, 0));  
	  
    private DefaultTreeModel m_model = new DefaultTreeModel(m_rootNode);  
    private JLabel linkLabel ;
    private JCheckBox checkBox;
    public String requestURL="http://localhost:8080/ShineHIS";
    
    public JCheckBox cbx_validate ;

    public static Map<String,String> cookie=null;
    
    private WebView browView;
    JFXPanel jfxPanel  ;
    private JLabel lbl_address ;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
//			String lookAndFeel =UIManager.getSystemLookAndFeelClassName();
//			lookAndFeel="com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
//			lookAndFeel ="com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel";
//			javax.swing.UIManager.setLookAndFeel(lookAndFeel);
			InitGlobalFont(new Font("宋 体", Font.PLAIN, 14));  //统一设置字体
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					App window = new App();
					window.frmv.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	private static void InitGlobalFont(Font font) {
		FontUIResource fontRes = new FontUIResource(font);
		for (Enumeration<Object> keys = UIManager.getDefaults().keys(); keys.hasMoreElements();) {
			Object key = keys.nextElement();
			Object value = UIManager.get(key);
			if (value instanceof FontUIResource) {
				UIManager.put(key, fontRes);
			}
		}
	}


	/**
	 * Create the application.
	 */
	public App() {
		try{
			if(!new File(System.getProperty("user.dir")+"/data.db").exists()){
				Toolkit.getDefaultToolkit().beep();
				JOptionPane.showMessageDialog(this.frmv, "数据库文件丢失", "提示",JOptionPane.ERROR_MESSAGE);
				System.exit(0);
			}
			if(sqlHelp.getConn()==null){
				Toolkit.getDefaultToolkit().beep();
				JOptionPane.showMessageDialog(this.frmv, "数据库连接失败,数据库文件可能己经损 坏", "提示",JOptionPane.ERROR_MESSAGE);
				System.exit(0);
			}
		}catch(Exception err){
			log.error(err);
		}
		initialize();
		initTree();
		txt_searchPath.addKeyListener(new KeyListener() {
			public void keyTyped(KeyEvent e) {
			}
			public void keyReleased(KeyEvent e) {
				DefaultMutableTreeNode node = searchNode(txt_searchPath.getText().trim());  
                if (node != null)  
                {  
                    TreeNode[] nodes = m_model.getPathToRoot(node);  
                    TreePath path = new TreePath(nodes);  
                    tree.scrollPathToVisible(path);                  
                    tree.setSelectionPath(path);
                    
                    Object object = node.getUserObject();
    				Category c = (Category) object;		
    				//category=c;
    				treeClick(node, c);
                }  
                else  
                {
                	
                }
			}
			public void keyPressed(KeyEvent e) {
			}
		});
	}
	
	public DefaultMutableTreeNode searchNode(String nodeStr)  
    {  
        DefaultMutableTreeNode node = null;  
        Enumeration e = m_rootNode.breadthFirstEnumeration();  
        while (e.hasMoreElements())  
        {  
            node = (DefaultMutableTreeNode) e.nextElement();  
            if (node.getUserObject()!=null && node.getUserObject().toString().indexOf(nodeStr)>=0)  
            {  
                return node;  
            }  
        }
        return null;  
    }  

	private MutableTreeNode getSibling(DefaultMutableTreeNode selNode)  
    {  
        MutableTreeNode sibling = (MutableTreeNode) selNode  
                .getPreviousSibling();  
        if (sibling == null)  
        {  
            sibling = (MutableTreeNode) selNode.getNextSibling();  
        }  
        return sibling;  
    }  
	
	public void fillTable(List<Param> params,String addMode) {
		DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
		if(addMode.equals("append")){
			//清涂之前的一个对象
			if(params.size()>0){
				String pro=params.get(0).getName().substring(0, params.get(0).getName().lastIndexOf('.'));
				for(int i=0;i<table.getRowCount();i++){
					String name=table.getModel().getValueAt(i, 0).toString().trim();
					if(name.equals(pro)){
						tableModel.removeRow(i);
						break;
					}
				}
			}
		}else if(addMode.equals("clean")){
			tableModel.setRowCount(0);// 清除原有行
		}
		// 填充数据
		for (Param param : params) {
			String[] arr = new String[3];
			arr[0] = param.getName();
			arr[1] = String.valueOf(param.getValue());
			// 添加数据到表格
			tableModel.addRow(arr);
		}

		// 更新表格
		table.invalidate();
		table.setModel(tableModel);
	}

	private void initTree(){		
		sqlHelp.setTreeNode(m_rootNode);
		TreeNode root = (TreeNode) tree.getModel().getRoot(); 
		
        tree.expandPath(new TreePath(root));
		
		
        //expandAll(tree, new TreePath(root), true);
        tree.updateUI();        
        this.requestURL = sqlHelp.querySetting(1);
        this.frmv.setTitle(this.frmv.getTitle()+"--"+this.requestURL);
        this.linkLabel.setText(this.requestURL);
            
	}

	//全局action
	Action action;
	//查询action和param
	private void treeClick(DefaultMutableTreeNode e, Category category) {
		
		//停止编辑
		if(table.isEditing()){
			table.getCellEditor().stopCellEditing();
		}		
		//如果有编辑,先保存一下
		menuSaveClick(null);
		
		Action a=sqlHelp.getActionByPid(category.getId());
		this.category=category;
		if(a != null){
			this.action=a;
			txt_url.setText(a.getUrl());
			comboBox.setSelectedItem(a.getMethod());
			this.checkBox.setSelected(action.isSer());
			List<Param> params = sqlHelp.getParamByActionId(a.getId());
			fillTable(params,"clean");			
		}else{
			this.action=null;
			txt_url.setText("");
			comboBox.setSelectedItem("GET");
			DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
			tableModel.setRowCount(0);
			tree.invalidate();
		}
		loadContent(" ");
	}
	//处理对象参数
	private void paramHandller(Map<String,Object> param,Map<String,Object> cParam,Map<String,Object> childObject){
		//处理子列表
		{
		//排序
			List<Map.Entry<String, Object>> list = new ArrayList<Map.Entry<String, Object>>(cParam.entrySet());
			Collections.sort(list, new Comparator<Map.Entry<String, Object>>() {  
	            public int compare(Entry<String, Object> o1, Entry<String, Object> o2) {  
	                return o2.getKey().toString().compareTo(o1.getKey().toString());  
	            }  
	        });		
			
			Set<String> set=new HashSet<String>();
			for (Map.Entry<String, Object> mapping : list) {  
				set.add(mapping.getKey().substring(0,mapping.getKey().indexOf('[')));
			}
			
			Set<String> set2=new HashSet<String>();
			for (Map.Entry<String, Object> mapping : list) {  
				set2.add(mapping.getKey().substring(0,mapping.getKey().indexOf('.')));
			}
			
			List<Map<String,Object>> child=new ArrayList<Map<String,Object>>();
			Map<String,Object> d=new HashMap<String,Object>();
			Iterator<String> it2=set2.iterator();
			String tmp="";
			Iterator<String> it=set.iterator();
			while(it.hasNext()){
				String it_key=it.next();
				it2=set2.iterator();			
				while(it2.hasNext()){
					String it2_key=it2.next();
					for (int i=0;i<list.size();i++) {
						Map.Entry<String, Object> mapping=list.get(i);
						if(!it2_key.equals(tmp)){
							d=new HashMap<String,Object>();
						}
			            if(mapping.getKey().startsWith(it2_key)){
			            	d.put(mapping.getKey().substring(mapping.getKey().indexOf('.')+1), cParam.get(mapping.getKey()));
			            }
			            tmp=it2_key;
			        }
					child.add(d);
				}
				param.put(it_key, child);
			}
		}
		
		//处理子对象
		{
			//目前先处理一个子对象
			Iterator it=childObject.keySet().iterator();
			Map<String,Object> newParam=new HashMap<String,Object>();
			String properName="";
			while(it.hasNext()){
				String key=it.next().toString();
				newParam.put(key.substring(key.indexOf('.')+1), childObject.get(key));
				if(properName.equals("")){
					properName=key.substring(0, key.indexOf('.'));
				}
			}
			if(!newParam.isEmpty()){
				param.put(properName, newParam);
			}
		}
		
	}
	private boolean myContains(List<Map.Entry<String, Object>> list1,List<Map.Entry<String, Object>> list2){
		for (Map.Entry<String, Object> mapping : list2) {  
			if(list1.contains(mapping)){
				return false;
			}
		}
		return true;
	}
	
	//开始请求
	private void btn_ProcessClick(ActionEvent e){

		//先登录
		String loginURL=this.requestURL+"/userAccount/login?json=%7B%22accountNo%22:%22admin%22,%22password%22:%22123456%22,%22userAccountName%22:%22%E6%9D%8E%E5%AF%8C%E5%BC%BA%22,%22RememberPwd%22:true%7D";

		Document doc;
		String result = "";		
		this.lbl_status.setText("");
		this.lbl_status.setBackground(Color.BLACK);
		this.lbl_jsonValidate.setText("");
		PlatformImpl.startup(new Runnable() {
            @Override
            public void run() {
            	browView.getEngine().load("about:blank");
            }
        });
		try {
			if(App.cookie==null && !this.cbx_validate.isSelected()) {
				Response res = Jsoup.connect(loginURL)
						.header("Host", "127.0.0.1:8000")
						.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0")
						.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
						.header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
						.header("Accept-Encoding", "gzip, deflate")
						.header("Connection", "keep-alive")
						.header("Upgrade-Insecure-Requests", "1")
						.header("Cache-Control", "max-age=0")
						.method(Method.GET).execute();
				App.cookie = res.cookies();
			}
			//组装参数
			Map param = new HashMap();
			Map<String,Object> childParam=new HashMap<String,Object>();
			Map<String,Object> childObject=new HashMap<String,Object>();
			for(int i=0;i<table.getRowCount();i++){
				//空值不传
				if(table.getModel().getValueAt(i, 0)==null){
					continue;
				}
				String name=table.getModel().getValueAt(i, 0).toString().trim();
				String value=table.getModel().getValueAt(i, 1)==null?"":table.getModel().getValueAt(i, 1).toString();
				if(name.indexOf('[')>=0 && name.indexOf(']')>=0){
					childParam.put(name, value);
					continue;
				}else if(name.indexOf('.')>0){
					childObject.put(name, value);
					continue;
				}
				if(!name.equals("")){
					param.put(name, value);
				}
			}
			
			//处理子对象
			paramHandller(param,childParam,childObject);
			
			long timestamp=(long)System.currentTimeMillis()/1000;
			Map<String,Object> realParam=new HashMap<String,Object>();
			realParam.put("key", "c445205ec25e4e1b991bcf9b311a429d");
			realParam.put("timestamp", timestamp);
			realParam.put("appid", "100001");
			String sign="{\"key\":\"c445205ec25e4e1b991bcf9b311a429d\",\"timestamp\":\"timestamp\",\"appid\":\"100001\"}";
			realParam.put("sign",MD5Util.md5Encode(sign));
			realParam.put("data", param);
			
			String paramJsonStr="{}";
			if(cbx_validate.isSelected()){
				paramJsonStr=JSONArray.toJSON(realParam).toString();
			}else{
				paramJsonStr=JSONArray.toJSON(param).toString();
			}
			

			log.info("请求参数:"+paramJsonStr);
			
			String linkUrl=this.requestURL+this.txt_url.getText().trim();
			if(comboBox.getSelectedItem().toString().equals("GET") || comboBox.getSelectedItem().toString().equals("DELETE")){				
				String url=this.requestURL+this.txt_url.getText();
				if(this.checkBox.isSelected() ){
					if(table.getRowCount()>0){
						if(url.indexOf('?')>0){
							url+="&json="+paramJsonStr;
							linkUrl+="&json="+URLEncoder.encode(paramJsonStr,"utf-8");
						}else{
							url+="?json="+paramJsonStr;
							linkUrl+="?json="+URLEncoder.encode(paramJsonStr,"utf-8");
						}
					}else{
						if(url.indexOf('?')>0){
							url+="&json="+paramJsonStr;
							linkUrl+="&json="+URLEncoder.encode(paramJsonStr,"utf-8");
						}else{
							url+="?json="+paramJsonStr;
							linkUrl+="?json="+URLEncoder.encode(paramJsonStr,"utf-8");
						}
					}
				}else{
					Iterator<String> it=param.keySet().iterator();
					while(it.hasNext()){
						String key=it.next();
						if(key.equals("")) continue;
						if(url.indexOf('?')>0){
							url+="&"+key+"="+param.get(key);
						}else{
							url+="?"+key+"="+param.get(key);
						}		
					}
				}
				
				linkLabel.setText(linkUrl);
				if(this.checkBox.isSelected()){
					if(this.cbx_validate.isSelected()){
						doc = Jsoup.connect(url).ignoreContentType(true).header("Content-type", "application/json; charset=utf-8").header("Accept", "application/json").timeout(1000*60).get();
					}else {
						doc = Jsoup.connect(url).cookies(cookie).ignoreContentType(true).header("Content-type", "application/json; charset=utf-8").header("Accept", "application/json").timeout(1000 * 60).get();
					}
				}else{
					if(this.cbx_validate.isSelected()) {
						doc = Jsoup.connect(url).ignoreContentType(true).timeout(1000 * 60).get();
					}else{
						doc = Jsoup.connect(url).cookies(cookie).ignoreContentType(true).timeout(1000 * 60).get();
					}
				}
				result = doc.body().select("body").text();
				
				JSONObject  ri=null;
			    try{
			    	ri =  JSONArray.parseObject(result);
			    }catch(JSONException err){
			    	lbl_status.setText("json转换异常");
			    	log.error("json转换异常");
			    	txt_Pane.setText(doc.body().select("body").html());
			    	return;
			    }
			    if(ri.getInteger("errorCode")==0){
			    	lbl_status.setText("请求正常");
			    	lbl_status.setForeground(Color.GREEN);
			    }else{
			    	lbl_status.setForeground(Color.RED);
			    	lbl_status.setText("请求异常");
			    	log.error("请求异常");
			    }
			    
			}else{
				
				Method method=Method.POST;
				if(comboBox.getSelectedItem().toString().equals("PUT")){
					method=Method.PUT;
				}
				Response response = null;
				if(this.checkBox.isSelected()){
//					Connection conn=Jsoup.connect().ignoreContentType(true).method(method).timeout(1000*60);//data("json", paramJsonStr);
//					conn.header("Content-type", "application/json; charset=utf-8").header("Accept", "application/json");
//					conn.timeout(1000*60);
//					conn.data("json",paramJsonStr);					
					result=HttpClient.post(this.requestURL+this.txt_url.getText(), paramJsonStr,comboBox.getSelectedItem().toString(),cookie);
				}else{
					response=Jsoup.connect(this.requestURL+this.txt_url.getText()).ignoreContentType(true).method(method).data(param)
							.cookies(cookie)
							.execute();
					result = response.body();
				}
				
							
				
				boolean ret = jsonValidator.validate(result);
				if(!ret){
					this.lbl_jsonValidate.setText("json验证失败");
					log.error(this.lbl_status.getText()+";json验证失败");
				}
				
				JSONObject  ri=null;
			    try{
			    	ri =  JSONArray.parseObject(result);
			    }catch(JSONException err){
			    	this.lbl_jsonValidate.setText("json转换异常");	    	
			    	log.error("json转换异常");
			    	txt_Pane.setText(result);
			    	return;
			    }			    
			    if(ri.getInteger("errorCode")==0){
			    	lbl_status.setText("请求正常");
			    	lbl_status.setForeground(Color.GREEN);
			    }else{
			    	lbl_status.setText("请求异常");
			    	this.lbl_status.setForeground(Color.RED);
			    	log.error("请求异常");
			    }
			}
			
			
			
			log.info(result);
		    
//			JsonFormatTool tool = new JsonFormatTool();
//			result=tool.formatJson(result);
//			result=JsonFormatUtil.formatJson(result);
			result="<style>.number{color:#EA7500}.boolean{color:green}.key{color:red}.string{color:#0080FF}.null{color:#CDCD9A}</style>"
					+ "<body></body><script> var data="+result+";"
					
					+ "function syntaxHighlight(json) {"
					+ "json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');"
					+ "return json.replace(/(\"(\\\\u[a-zA-Z0-9]{4}|\\\\[^u]|[^\\\\\"])*\"(\\s*:)?|\\b(true|false|null)\\b|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)/g, function (match) {"
					+ "   var cls = 'number';"
					+ "   if (/^\"/.test(match)) {"
							+ "      if (/:$/.test(match)) {"
							+ "      cls = 'key';"
							+ " } else {"
							+ "   cls = 'string';"
							+ " }"
							+ "  } else if (/true|false/.test(match)) {"
							+ "      cls = 'boolean';"
							+ "  } else if (/null/.test(match)) {"
							+ "      cls = 'null';"
							+ "  }		"
							+ "   return '<span class=\"' + cls + '\">' + match + '</span>';"
							+ " });}"
							+ "var str = JSON.stringify(data, undefined, 4);document.body.appendChild(document.createElement('pre')).innerHTML = syntaxHighlight(str);"
							+ "</script>";
			
			loadContent(result);
			
					
			//处理颜色
//			StringBuilder sb=new StringBuilder();
//			int mindex=0;
//			for(int i=0;i<result.length();i++){
//				if(result.charAt(i)=='"'){					
//					if (mindex%2==0){
//						sb.append("<span color='orange'>\"");
//					}else{
//						sb.append("\"</span>");
//					}					
//					++mindex;
//				}else{
//					sb.append(result.charAt(i));
//				}
//			}
//			result=sb.toString();
			
			//String js="	public String syntaxHighlight(String json) {	    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');	    return json.replace(/(\"(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\\"])*\"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {	        var cls = 'number';	        if (/^\"/.test(match)) {	            if (/:$/.test(match)) {	                cls = 'key';	            } else {	                cls = 'string';	            }	        } else if (/true|false/.test(match)) {	            cls = 'boolean';	        } else if (/null/.test(match)) {	            cls = 'null';	        }	        return '<span class=\"' + cls + '\">' + match + '</span>';	    });	}";
			
			
			
		}catch(HttpStatusException e2){
			e2.printStackTrace();
			lbl_status.setForeground(Color.red);
			lbl_status.setText(e2.getStatusCode()+":"+e2.getMessage());
			
		}catch(JSONException e3){
			log.error(e3);
			this.lbl_jsonValidate.setText("json转换异常:"+e3.getMessage());
		}catch (Exception e1) {
			e1.printStackTrace();
			log.error("dsfds"+e1);
			lbl_status.setForeground(Color.red);
			lbl_status.setText(e1.getMessage());
		}finally {
//			txt_Pane.setText(result);
		}
	}
	private void loadContent(String content){
		
		PlatformImpl.startup(new Runnable() {
            public void run() {
              browView.getEngine().loadContent(content);
            }
        });
	}
	//展开树 
	private void expandAll(JTree tree, TreePath parent, boolean expand) { 
        TreeNode node = (TreeNode) parent.getLastPathComponent(); 
        if (node.getChildCount() >= 0) { 
            for (Enumeration e = node.children(); e.hasMoreElements(); ) { 
                TreeNode n = (TreeNode) e.nextElement(); 
                TreePath path = parent.pathByAddingChild(n); 
                tree.expandPath(path);
                //expandAll(tree, path, expand); 
            } 
        }
	}
	
	private void menuItem_addClick(ActionEvent e){
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
		Category c = (Category) node.getUserObject();
		DefaultMutableTreeNode cnode = new DefaultMutableTreeNode(new Category("未命名", 0, c.getId()));
		node.add(cnode);
		
		TreeNode root = (TreeNode) tree.getModel().getRoot(); 
        //expandAll(tree, new TreePath(root), true);
        tree.updateUI();
        
        //定位
        TreeNode[] nodes = m_model.getPathToRoot(cnode);  
        TreePath path = new TreePath(nodes);  
        tree.scrollPathToVisible(path);
        tree.setSelectionPath(path);
        tree.startEditingAtPath(path);
        
	}
	private void menuItem_delClick(ActionEvent e){
		
		if(JOptionPane.showConfirmDialog(this.frmv, "确定要删除吗", "确定要删除吗", JOptionPane.OK_CANCEL_OPTION,JOptionPane.WARNING_MESSAGE)==JOptionPane.OK_OPTION){
		
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
			Category c = (Category) node.getUserObject();
			sqlHelp.deleteTree(c.getId());
			node.removeFromParent();
			//node.removeFromParent();
			tree.updateUI();
		}
       
	}
	private void menuItem_update(ActionEvent e){
//		MyAppUpdate t=new MyAppUpdate();
	}
	
	private void btn_addRowClick(ActionEvent e){
		DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
		tableModel.addRow(new   Vector());
	}
	private void btn_delClick(ActionEvent e){
		DefaultTableModel tableModel = (DefaultTableModel) table.getModel();		
		int[] rows = table.getSelectedRows();
        if(rows.length   >   0)
        {
        	for (int i : rows) {
        		tableModel.removeRow(i);
			}
        }
        
        table.updateUI();
        if(tableModel.getRowCount()>0){
        	table.setRowSelectionInterval(0, 0);
        }
	}
	
	//当前的分类
	private Category category;

	//组件自适应问题
	private void frmResize(){
		Rectangle rect_s1_old=scrollPane_1.getBounds();
		Rectangle rect2_s1_new=new Rectangle(rect_s1_old.x, rect_s1_old.y, scrollPane_1.getParent().getBounds().width-10 , rect_s1_old.height);
		scrollPane_1.setBounds(rect2_s1_new);
		try {
			Thread.currentThread().sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		if(jfxPanel!=null && jfxPanel.getParent()!=null){
			Rectangle rect_s_old=jfxPanel.getBounds();
			int rect_s_old_height=jfxPanel.getParent().getBounds().height-rect2_s1_new.height-12;
			Rectangle rect_s_new=new Rectangle(rect_s_old.x, rect_s_old.y, jfxPanel.getParent().getBounds().width-10 , rect_s_old_height-25);
			jfxPanel.setBounds(rect_s_new);
		}
		frmv.invalidate();
	}
	
	private void showParamDialog(ActionEvent e){
		List<String> param=new ArrayList<String>();
		for(int i=0;i<table.getRowCount();i++){
			//空值不传
			String name=table.getModel().getValueAt(i, 0).toString().trim();
			if(name.indexOf('[')>=0 && name.indexOf(']')>=0){
				continue;
			}else if(name.indexOf('.')>0){
				continue;
			}else{
				param.add(name);
			}
		}
		
		ParamDialog dialog=new ParamDialog(this,this.frmv,param);
		dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		dialog.setModal(true);
		dialog.setVisible(true);
	}
	private void showSettingDialog(){
		Setting dialog=new Setting(this);
		dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		dialog.setModal(true);
		dialog.setVisible(true);
	}
	
	private void tableChange(){
		this.lbl_address.setText("地址*:");
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {

		frmv = new JFrame();
		frmv.setTitle("\u6D4B\u8BD5\u5DE5\u5177V0.0.6");
		frmv.setBounds(100, 100, 1205, 833);
		frmv.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		
		
//		ImageIcon icon = new ImageIcon(this.getClass().getResource("image/bug.gif"));
//		frmv.setIconImage(icon.getImage());
		
		frmv.setExtendedState( Frame.MAXIMIZED_BOTH );		
		frmv.addWindowStateListener(new WindowStateListener() {
			public void windowStateChanged(WindowEvent e) {				
//				frmResize();
			}
		});
		frmv.addComponentListener(new ComponentListener() {
			public void componentShown(ComponentEvent e) {
				frmResize();
			}
			public void componentResized(ComponentEvent e) {
				frmResize();
			}
			public void componentMoved(ComponentEvent e) {
				frmResize();
			}
			public void componentHidden(ComponentEvent e) {
				frmResize();
			}
		});

		JPanel panel = new JPanel();
		frmv.getContentPane().add(panel, BorderLayout.NORTH);
		panel.setLayout(new BorderLayout(0, 0));

		JMenuBar menuBar = new JMenuBar();
		panel.add(menuBar);

		JPanel panel_1 = new JPanel();
		panel.add(panel_1, BorderLayout.SOUTH);
		panel_1.setLayout(new BorderLayout(0, 0));

		JToolBar toolBar = new JToolBar();
		panel_1.add(toolBar);
		
		cbx_validate = new JCheckBox("\u6743\u9650\u6821\u9A8C");
		toolBar.add(cbx_validate);
		
		JButton btnNewButton = new JButton("^_^");
		toolBar.add(btnNewButton);
		
		linkLabel = new JLabel("http://182.92.218.212:8080/");
		linkLabel.setForeground(Color.BLUE);
		linkLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));	
		linkLabel.addMouseListener(new MouseAdapter() {
             
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                	JLabel jlabel=(JLabel)e.getSource();
                    Desktop.getDesktop().browse(new URI(jlabel.getText()));
                } catch (IOException err) {
                    err.printStackTrace();
                } catch (URISyntaxException err) {
                    err.printStackTrace();
                }
            }
        });
		
		
		toolBar.add(linkLabel);
		

		JSplitPane splitPane = new JSplitPane();
		frmv.getContentPane().add(splitPane, BorderLayout.CENTER);
		splitPane.setDividerLocation(160);
		//定义表头
		String[] headers = { "参数", "值" };
		Object[][] cellData = null;
			

		JMenu menu = new JMenu("开始");
		JMenu menuAbout = new JMenu("关于");
		menuBar.add(menu);
		menuBar.add(menuAbout);
		JMenuItem menuItem_edit = new JMenuItem("编辑");
		menu.add(menuItem_edit);
		menuItem_edit.addActionListener(new ActionListener() {			
			public void actionPerformed(ActionEvent e) {
				showSettingDialog();
				
			}
		});
		
		JMenuItem menuItem_about = new JMenuItem("城市查询");
		menu.add(menuItem_about);
		menuItem_about.addActionListener(new ActionListener() {			
			public void actionPerformed(ActionEvent e) {
				About about=new About(null);
				about.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
				about.setModal(true);
				about.setVisible(true);
				
			}
		});
		
		JMenuItem menuItem_save = new JMenuItem("保存");
		menuItem_save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
		menuItem_save.setMnemonic('F');
		menuItem_save.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				menuSaveClick(e);
			}
		});
		
		JMenuItem menuItem_update  = new JMenuItem("更新...");
		menuItem_update.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				menuItem_update(e);
			}
		});
		
		menu.add(menuItem_save);
		menu.addSeparator();
		
		JMenuItem menuItem_exit = new JMenuItem("退出");
		menu.add(menuItem_exit);
		menuAbout.add(menuItem_update);
		
		JPanel panel_5 = new JPanel();
		panel_5.setLayout(new BorderLayout(0, 0));
		tree = new JTree(m_rootNode);
		panel_5.add(tree);
		splitPane.setLeftComponent(panel_5);
		
		//树选择事件
		tree.addTreeSelectionListener(new TreeSelectionListener() {
			public void valueChanged(TreeSelectionEvent e) {
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
				if (node == null)
					return;
				Object object = node.getUserObject();
				Category c = (Category) object;		
				category=c;
				//category=c;
				treeClick(node, c);
				
				if (node.isLeaf()) {
				}else{
				}
			}
		});
		//树编辑事件
		tree.getModel().addTreeModelListener(new TreeModelListener() {
			
			@Override
			public void treeStructureChanged(TreeModelEvent e) {
			}
			
			@Override
			public void treeNodesRemoved(TreeModelEvent e) {
			}
			
			@Override
			public void treeNodesInserted(TreeModelEvent e) {
			}
			
			@Override
			public void treeNodesChanged(TreeModelEvent e) {
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
				if (node == null)
					return;
				Object object = node.getUserObject();
				if (node.isLeaf()) {
					DefaultMutableTreeNode parent=(DefaultMutableTreeNode) node.getParent();
					Category parentCategory = (Category) (parent.getUserObject());
					Category c=new Category(object.toString(),category.getId(),parentCategory.getId());
					c=sqlHelp.saveTree(c);
					node.setUserObject(c);
					tree.invalidate();
				}
//				txt_url.setText("");
//				txt_Pane.setText("");
				checkBox.setSelected(true);
//				DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
//				tableModel.setRowCount(0);
				tree.invalidate();
			}
		});
		tree.updateUI();
		
		JPopupMenu popupMenu = new JPopupMenu();
		JMenuItem menuItem_add = new JMenuItem("添加");
		menuItem_add.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				menuItem_addClick(e);
			}
		});
		JMenuItem menuItem_del = new JMenuItem("删除");
		menuItem_del.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				menuItem_delClick(e);
			}
		});
		
		
		
		
		popupMenu.add(menuItem_add);
		popupMenu.add(menuItem_del);
		addPopup(tree, popupMenu);
		tree.setEditable(true);
		
		txt_searchPath = new JTextField();
		panel_5.add(txt_searchPath, BorderLayout.NORTH);
		txt_searchPath.setColumns(10);
		

		JPanel panel_2 = new JPanel();
		splitPane.setRightComponent(panel_2);
		panel_2.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_4 = new JPanel();
		panel_2.add(panel_4,BorderLayout.NORTH);
		FlowLayout fl_panel_4 = new FlowLayout(FlowLayout.LEFT, 5, 5);
		fl_panel_4.setAlignOnBaseline(true);
		panel_4.setLayout(fl_panel_4);
		
		lbl_address = new JLabel("地址:");
		panel_4.add(lbl_address);
				
		txt_url = new JTextField();
		panel_4.add(txt_url);
		txt_url.setColumns(35);
		
				comboBox = new JComboBox<String>();
				panel_4.add(comboBox);
				
				JButton btn_Process = new JButton("\u6267\u884C");
				panel_4.add(btn_Process);
				
				JButton btn_addRow = new JButton("\u6DFB\u52A0");
				panel_4.add(btn_addRow);
				btn_addRow.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						btn_addRowClick(e);
					}
				});
				
				JButton btn_addBatchParam = new JButton("\u6279\u91CF\u6DFB\u52A0\u53C2\u6570");
				btn_addBatchParam.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						showParamDialog(e);
					}
				});
				panel_4.add(btn_addBatchParam);
				
				JButton btn_del = new JButton("\u5220\u9664");
				panel_4.add(btn_del);
				
				checkBox = new JCheckBox("\u5E8F\u5217\u5316\u53C2\u6570");
				checkBox.setSelected(true);
				panel_4.add(checkBox);
				
				JButton btn_copyClipboard = new JButton("\u590D\u5236JSON\u53C2\u6570");
				btn_copyClipboard.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						//组装参数
						Map param = new HashMap();
						Map<String,Object> childParam=new HashMap<String,Object>();
						Map<String,Object> childObject=new HashMap<String,Object>();
						for(int i=0;i<table.getRowCount();i++){
							//空值不传
							String name=table.getModel().getValueAt(i, 0).toString().trim();
							String value=table.getModel().getValueAt(i, 1).toString();
							if(name.indexOf('[')>=0 && name.indexOf(']')>=0){
								childParam.put(name, value);
								continue;
							}else if(name.indexOf('.')>0){
								childObject.put(name, value);
								continue;
							}else{
								param.put(name, value);
							}
						}
						
						//处理子对象
						paramHandller(param,childParam,childObject);
						String jsonstr=JSONArray.toJSONString(param);
						Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard(); 
			            Transferable tText = new StringSelection(jsonstr); 
			            clip.setContents(tText, null); 
					}
				});
				panel_4.add(btn_copyClipboard);
				
				JButton btn_ClipboardValidate = new JButton("\u4ECE\u526A\u8D34\u677F\u6821\u9A8C");
				btn_ClipboardValidate.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						clipboardValidateClick();
					}
				});
				panel_4.add(btn_ClipboardValidate);
				btn_del.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						btn_delClick(e);
					}
				});
				btn_Process.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						btn_ProcessClick(e);
					}
				});
				comboBox.addItem("POST");
				comboBox.addItem("GET");
				comboBox.addItem("PUT");
				comboBox.addItem("DELETE");
				
				JPanel panel_3 = new JPanel();
				panel_2.add(panel_3);
				panel_3.setLayout(null);
				
				scrollPane_1 = new JScrollPane();
				scrollPane_1.setBounds(5, 5, 1022, 223);
				panel_3.add(scrollPane_1);
				
				
				DefaultTableModel model = new DefaultTableModel(cellData, headers) {
					private static final long serialVersionUID = 1L;
					public boolean isCellEditable(int row, int column) {
						tableChange();
						return true;
					}
				};
				model.addTableModelListener(new TableModelListener() {			
					public void tableChanged(TableModelEvent e) {
//						tableChange();
					}
				});				
				
				
				table = new JTable();
				table.setModel(model);
				table.setRowHeight(25);;
				table.addKeyListener(new KeyListener() {
					public void keyTyped(KeyEvent e) {
					}
					public void keyReleased(KeyEvent e) {
					}
					public void keyPressed(KeyEvent e) {
						tableChange();												
					}
				});
				table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
//				table.add
				
				scrollPane_1.setViewportView(table);	
				scrollPane = new JScrollPane();
				scrollPane.setBounds(5, 260, 1022, 581);
				scrollPane.getVerticalScrollBar().setUnitIncrement(20);
//				panel_3.add(scrollPane);				
				scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
				
				JPanel panel_6 = new JPanel();
				scrollPane.setViewportView(panel_6);
				panel_6.setLayout(new BorderLayout(0, 0));
				
				txt_Pane = new JEditorPane();
				//panel_6.add(txt_Pane);
				txt_Pane.setContentType("text/javascript");
				
				PlatformImpl.startup(new Runnable() {
		            @Override
		            public void run() {
		                jfxPanel = new JFXPanel();
		                browView = new WebView();
		                final StackPane layout = new StackPane();		 
		                Scene scene = new Scene(layout);		 
		                layout.getChildren().addAll(browView);
		                
		                jfxPanel.setScene(scene);
		                jfxPanel.setVerifyInputWhenFocusTarget(true);
//		                browView.getEngine().load("http://www.baidu.com");
		                jfxPanel.setBounds(5, 260, 1022, 581);
		                panel_3.add(jfxPanel);
		            }
		        });
				
								
				
				lbl_status = new JLabel("\u7ED3\u679C");
				lbl_status.setBounds(15, 238, 668, 15);
				panel_3.add(lbl_status);
				lbl_status.setFont(new Font("宋体", Font.BOLD, 12));
				
				lbl_jsonValidate = new JLabel("");
				lbl_jsonValidate.setForeground(Color.RED);
				lbl_jsonValidate.setBounds(326, 238, 54, 15);
				panel_3.add(lbl_jsonValidate);
				menuItem_exit.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					exitClick(e);
				}		
				
		});
	}
	
	private void clipboardValidateClick() {
		Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard(); 
        Transferable tText = clip.getContents(null);
        String value="";
        if (tText != null) {
            // 检查内容是否是文本类型
        	if (tText.isDataFlavorSupported(DataFlavor.stringFlavor)){
        		try {
					value = (String)tText.getTransferData(DataFlavor.stringFlavor);
					JsonValidator validator=new JsonValidator();
					if(!validator.validate(value)){
						//JOptionPane.showConfirmDialog(this.frmv, "JSON解析错误");
						value=new JsonFormatTool().formatJson(value);
						loadContent(value);
					}else{					
					String result="<style>.number{color:#EA7500}.boolean{color:green}.key{color:red}.string{color:#0080FF}.null{color:#CDCD9A}</style>"
							+ "<body></body><script> var data="+value+";"
							
							+ "function syntaxHighlight(json) {"
							+ "json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');"
							+ "return json.replace(/(\"(\\\\u[a-zA-Z0-9]{4}|\\\\[^u]|[^\\\\\"])*\"(\\s*:)?|\\b(true|false|null)\\b|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)/g, function (match) {"
							+ "   var cls = 'number';"
							+ "   if (/^\"/.test(match)) {"
									+ "      if (/:$/.test(match)) {"
									+ "      cls = 'key';"
									+ " } else {"
									+ "   cls = 'string';"
									+ " }"
									+ "  } else if (/true|false/.test(match)) {"
									+ "      cls = 'boolean';"
									+ "  } else if (/null/.test(match)) {"
									+ "      cls = 'null';"
									+ "  }		"
									+ "   return '<span class=\"' + cls + '\">' + match + '</span>';"
									+ " });}"
									+ "var str = JSON.stringify(data, undefined, 4);document.body.appendChild(document.createElement('pre')).innerHTML = syntaxHighlight(str);"
									+ "</script>";
					
					loadContent(result);
					}
				} catch (UnsupportedFlavorException | IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}        		
        	}
        }
	}
	
	//保存快捷键事件
	public void menuSaveClick(ActionEvent r){
		
		try{
			//获取所有参数
			List<Param> params = new ArrayList<Param>();
			for(int i=0;i<table.getRowCount();i++){
				if(table.getModel().getValueAt(i, 0)==null){
					continue;
				}
				
				String _name = table.getModel().getValueAt(i, 0).toString();
				String _value = table.getModel().getValueAt(i, 1)==null?"":table.getModel().getValueAt(i, 1).toString();
				Param param=new Param();
				param.setName(_name);
				param.setValue(_value);
				params.add(param);
			}
			if(action==null){
				action=new Action();
			}
			String str=this.txt_url.getText();
			//str=str.substring(str.indexOf("/inp"));
			action.setUrl(str);
			action.setMethod(this.comboBox.getSelectedItem().toString());
			action.setSer(this.checkBox.isSelected());
			Action a2=sqlHelp.saveAction(action,category,params);
			if(a2!=null){
				this.lbl_address.setText("地址:");
			}
		}catch(Exception err){
			log.error("保存异常",err);
		}
	}

	private void exitClick(ActionEvent e) {
		System.exit(0);
	}

	//控件样式
//	public static String[] DEFAULT_FONT = new String[] { "Table.font", "TableHeader.font", "CheckBox.font", "Tree.font",
//			"Viewport.font", "ProgressBar.font", "RadioButtonMenuItem.font", "ToolBar.font", "ColorChooser.font",
//			"ToggleButton.font", "Panel.font", "TextArea.font", "Menu.font", "TableHeader.font"
//			// ,"TextField.font"
//			, "OptionPane.font", "MenuBar.font", "Button.font", "Label.font", "PasswordField.font", "ScrollPane.font",
//			"MenuItem.font", "ToolTip.font", "List.font", "EditorPane.font", "Table.font", "TabbedPane.font",
//			"RadioButton.font", "CheckBoxMenuItem.font", "TextPane.font", "PopupMenu.font", "TitledBorder.font",
//			"ComboBox.font" };
	private JTextField txt_searchPath;
	private static void addPopup(Component component, final JPopupMenu popup) {
		component.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}
			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}
			private void showMenu(MouseEvent e) {
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		});
	}
}
